package com.aliware.tianchi.loadbalance;

import org.apache.dubbo.rpc.Invoker;

import java.util.List;

public class WeightTools {


    /**
     * 响应时间权重分配
     *
     */
    public static <T> Invoker<T> next(List<WeightNode<Invoker<T>>> nodes){
        int length = nodes.size();
        if(length==0){
            return null;
        }
        double allKeys = 0;
        for (int i=0;i<length;i++){
            WeightNode<?> node = nodes.get(i);
            double t = node.getAvg();
            double value = 0;
            for(int j=0;j<length;j++){
                value+=t/nodes.get(j).getAvg();
            }
            double res = 1/value;
            node.setAround(allKeys, allKeys+=res);
        }
        double val = Math.random();
        for (WeightNode<Invoker<T>> node:nodes){
            if(node.exist(val)){
                return  node.getValue();
            }
        }
        return null;
    }


    /**
     * 响应与并发量的权重分配
     */
    public static <T> Invoker<T> get(List<WeightNode<Invoker<T>>> nodes){
        int length = nodes.size();
        if(length==0){
            return null;
        }
        double allKeys = 0;
        int R = CodingApiLoadBalance.POOL_SIZE;
        for (int i=0;i<length;i++){
            WeightNode<?> node = nodes.get(i);
            double t = node.getAvg();
            double c = node.getChannels();
            double value = 0;
            for(int j=0;j<length;j++){
                WeightNode<?> nodeJ = nodes.get(j);
                double v1 = t * nodeJ.getChannels();
                double v2 = c * nodeJ.getAvg();
                value+=(v1)/(v2);
            }
            double number = (R/value);
            double res = number/R;
            node.setAround(allKeys, allKeys+=res);
        }
        double val = Math.random();
        for (WeightNode<Invoker<T>> node:nodes){
            if(node.exist(val)){
                return  node.getValue();
            }
        }
        return null;
    }




}
